<template>
  <div class="index">
    <v-header></v-header>
    <div class="search">
      <el-input clearable v-model="searchName" placeholder="请输入商品名称" style="width: 200px;"></el-input>
      <el-button type="primary" style="width: 80px; margin-left: 10px;" @click="searchBtn">搜索</el-button>
    </div>
    <div class="listTit">
      <p>商品列表</p>
    </div>
    <div class="listMsg">
      <div class="list">
        <!-- <div> -->
          <div class="item" :key="index" v-for="(item, index) in list" @mouseenter="enter(index)" @mouseleave="leave()">
            <div class="img">
              <img :src="item.img_url">
            </div>
            <div class="msg">
              <p class="tit">{{item.goods_name}}</p>
              <div class="tagList">
                <p>55英寸</p>
                <p>黑色</p>
              </div>
              <div class="price">
                <span>￥{{item.discount_price}}</span>
                <el-input-number v-show="seen&&index==current" :min="0" size="mini" v-model="item.count" :step="1"></el-input-number>
              </div>
            </div>
          </div>
        <!-- </div> -->

        <div class="pagination">
          <el-pagination
            background
            v-if="total>10"
            :page-size="page_size"
            :total="total"
            style=""
            ref="pagination"
            @current-change="pageChange">
          </el-pagination>
        </div>
      </div>
      <div class="cart">
        <div class="tit">
          <p>购物车</p>
<!--          <p>删除选中商品</p>-->
        </div>
        <div class="checked" v-if="list">
          <el-checkbox-group v-model="checkList">
            <div class="item" :key="index" v-for="(item, index) in list" v-if="item.count">
                <el-checkbox :key="item.goods_id" :label="item.goods_id" style="display:flex;align-items:center;"><span style="display: none">1</span></el-checkbox>
                <div class="wares">
                  <img :src="item.img_url">
                  <div class="msg">
                    <p class="waretit">{{item.goods_name}}</p>
                    <div class="namelist">
                      <p>55英寸</p>
                      <p>黑色</p>
                    </div>
                    <div class="bottom">
                      <p class="price">￥{{item.discount_price}}</p>
                      <div>
                        <el-input-number @change="countChange($event,item.goods_id)" size="small" v-model="item.count" :min="0" :step="1"></el-input-number>
                      </div>
                    </div>
                  </div>
                </div>
            </div>
          </el-checkbox-group>
        </div>
        <div class="allCheck">
        <el-checkbox v-model="all" @change="allChange"></el-checkbox>
        <div class="msg">
          <p>已选 <span>{{count}}</span>件商品</p>
          <p>共计：（不含运费）￥ <span>{{price}}</span>元</p>
        </div>
        <p class="submit" @click="create">去结算</p>
      </div>

      </div>
    </div>
  </div>
</template>
<script>
  import {productList} from '../../api/ajax'
  import header from '../common/header'
  import { mapActions } from 'vuex'
  export default{
    data () {
      return {
        searchName: '',
        checkList: [],
        list: [],
        num: 1,
        all: false,
        productCount:0,
        seen:false,
        current:0,
        cartList: [],
        count: 0,
        price: 0,
        isFirstEnter:false,
        selectList: [],
        page_size: 10,
        page_num: 1,
        total:0
      }
    },
    watch: {
      checkList: {
        handler(newName, oldName) {
          if (newName.length) {
            let newPrice = 0
            let newCount = 0
            this.selectList = []
            newName.forEach(item => {
              this.selectList.push(this.list.filter(it => it.goods_id ===  item)[0])
            })
            if (this.selectList.length!== this.list.filter(item => item.count).length) {
              this.all = false
            } else {
              this.all = true
            }
            this.selectList.forEach(item => {
              if (item.count) {
                // console.log(item.count,item.market_price)
                let itemPrice = (Number(item.count) * Number(item.discount_price))
                newPrice += itemPrice
                newCount += item.count
              }
            })
            this.price=newPrice
            this.count=newCount
          } else {
            this.price=0
            this.count=0
            this.all = []
          }
        },
        deep: true,
        immediate: true
      }
    },
    beforeRouteEnter(to, from, next) {
      if (from.name == "settleAccounts") {
        // 这个name是下一级页面的路由name
        to.meta.isBack = true; // 设置为true说明你是返回到这个页面，而不是通过跳转从其他页面进入到这个页面
      }
      next();
    },
    activated() {
      console.log('activated')
      let _this = this;
      if(!_this.$route.meta.isBack || _this.isFirstEnter){
        _this.name =  '';
        _this.checkList =  [];
        _this.list =  [];
        _this.num =  1;
        _this.all =  '';
        _this.productCount = 0;
        _this.seen = false;
        _this.current = 0;
        _this.cartList =  [];
        _this.count =  0;
        _this.price =  0;
        _this.isFirstEnter = false; // 定义变量来判断是否第一次进入，默认false
        _this.getProductList();
      }
       // // 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据
      _this.$route.meta.isBack=false;
       // // 恢复成默认的false，避免isBack一直是true，导致每次都获取新数据
      _this.isFirstEnter=false;
    },
    mounted(){
      console.log('mounted')
    },
    components: {'v-header': header},
    methods: {
      ...mapActions([
        'updateSelectList'
      ]),
      // chooseCart(val){
      //   let arr = [];
      //   this.price = 0;
      //   val.forEach(function(element){
      //     let id = element.substring(0, element.lastIndexOf('_'));
      //     arr.push(id);
      //   })
      //   console.log(arr);
      //   this.count = arr.length;
      //   console.log(this.list);
      //   let priceList = [];
      //   this.list.forEach(function(element) {
      //     arr.forEach(function(element2) {
      //       if(element.goods_id == element2){
      //         console.log(element.goods_name)
      //         priceList.push(element.market_price*element.count);
      //       }
      //     })
      //   })
      //   console.log(priceList)
      //   for(let i = 0; i < priceList.length; ++i) {
      //       this.price += priceList[i];
      //   }
      //   // console.log(result);
      //   // this.price
      // },
      searchBtn(){
        console.log(this.searchName)
        this.$nextTick(() => {
            this.$refs.pagination.internalCurrentPage = 1;
        })
        this.page_num = 1;
        this.page_size = 10;
        productList({
          page: this.page_num,
          page_size: this.page_size,
          goods_name:this.searchName
        }).then(res => {
          console.log(res);
          if (res.data.code === 1) {
            res.data.data.list.forEach(item => {
              item['count'] = 0
            })
            this.list = res.data.data.list;
            this.total = parseInt(res.data.data.count);
          }
        })
      },
      pageChange(val){
        console.log(val)
        this.page_num = val;
        this.getProductList();
      },
      getProductList(){
        productList({
          page: this.page_num,
          page_size: this.page_size,
        }).then(res => {
          console.log(res);
          if (res.data.code === 1) {
            res.data.data.list.forEach(item => {
              item['count'] = 0
            })
            this.list = res.data.data.list;
            this.total = parseInt(res.data.data.count);
          }
        })
      },
      goSettleAccounts(){
        this.$router.push({
          name: 'settleAccounts',
        })
      },
      enter(index){
        this.seen = true;
        this.current = index;
      },
      countChange(e,id){
        console.log(e)
        if (e) {
          let newPrice = 0
          let newCount = 0
          let arr = []
          this.checkList.forEach(item => {
            arr = this.list.filter(it => it.goods_id === item)
            if (arr.length) {
              let itemPrice = (Number(arr[0].count) * Number(arr[0].discount_price))
              newPrice += itemPrice
              newCount += arr[0].count
            }
          })
          this.count=newCount
          this.price=newPrice
        } else {
          this.checkList.splice(this.checkList.indexOf(id),1)
        }
      },
      allChange(e){
        console.log(e)
        if (e) {
          this.checkList = []
          this.list.forEach(item => {
            if (item.count) {
              this.checkList.push(item.goods_id)
            }
          })
        } else {
          this.checkList = []
        }
      },
      leave(){
        this.seen = false;
        this.current = null;
      },
      goodsList(value,id) {
        let goods = this.list.filter(item=> item.product_id===id)
        console.log(value,id,this.list)
      },
      create() {
        let arr = []
        let _this = this;
        console.log(_this.selectList)
        if (_this.selectList.length) {

          this.updateSelectList( _this.selectList)
          _this.$store.state.selectList = _this.selectList
          _this.$router.push({
            name: 'settleAccounts',
          })
        } else {
          _this.$message.warning('请选择商品')
        }
      },
    },
    created(){
      this.isFirstEnter=true;
    }
  };
</script>
<style scoped>
  .submit{
    width: 100px;
    height: 35px;
    border: 1px solid #eaeaea;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    margin-left: 50px;
    background: #409EFF;
    color: #fff;
    cursor: pointer;
  }
  .allCheck .msg p span{
    color: #ff6666;
  }
  .allCheck .msg p{
    font-size: 14px;
    line-height: 24px;
    color: #333;
    margin-left: 10px;
  }
  .allCheck{
    position: absolute;
    left: 0;
    bottom: 0;
    height: 70px;
    padding-left: 10px;
    padding-right: 10px;
    display: flex;
    align-items: center;
  }
  .cart .checked{
    height: 480px;
    overflow-y: auto;
  }
  .cart .checked .item .wares .msg .bottom{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 8px;
  }
  .cart .checked .item .wares .msg .bottom .price{
    font-size: 14px;
    line-height: 14px;
    color:#FF6666;
    margin-top: 8px;
  }
  .cart .checked .item .wares .msg .namelist{
    display: flex;
  }
  .cart .checked .item .wares .msg .namelist p{
    font-size: 14px;
    line-height: 14px;
    color: #333;
    padding: 3px 5px;
    background: #f2f2f2;
    border-radius: 4px;
    margin-right: 5px;
    margin-top: 5px;
  }
  .cart .checked .item .wares .msg .waretit{
    width: 100%;
    font-size: 16px;
    line-height: 22px;
    color: #333;
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .cart .checked .item .wares .msg{
    margin-left: 10px;
  }
  .cart .checked .item .wares img{
    width: 100px;
    height: 100px;
    margin-left: 10px;
  }
  .cart .checked .item .wares{
    display: flex;
    align-items: center;

  }
  .cart .checked .item{
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #eaeaea;
  }
  .pagination{
    width: 1200px;
    height: 60px;
    margin: 0 auto;
    display: flex;
    justify-content: center;
  }
  .listMsg .list .msg .price{
    height: 30px;
    margin-top: 12px;
  }
  .listMsg .list .msg .price span{
     display: inline-block;
     font-size: 16px;
     line-height: 30px;
     color: #FF6666;
   }
  .listMsg .list .msg .price span{

  }
  .listMsg .list .msg .tagList{
    display: flex;
    margin-top: 8px;
  }
  .listMsg .list .msg .tagList p{
    padding: 2px 5px;
    background: #f2f2f2;
    border-radius: 4px;
    margin-right: 5px;
    font-size: 14px;
    line-height: 14px;
    color: #333;
  }
  .listMsg .list .msg{
    padding-right: 20px;
    margin-left: 10px;
  }
  .listMsg .list .msg .tit{
    font-size: 16px;
    line-height: 22px;
    color: #333;
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .cart .tit{
    display: flex;
    align-items: center;
    height: 50px;
    border-bottom: 1px solid #eaeaea;
    padding: 0 10px;
    justify-content: space-between;
  }
  .cart .tit p:nth-child(1){
    font-size: 18px;
    line-height: 18px;
    color: #333;
  }
  .cart .tit p:nth-child(2){
    font-size: 14px;
    line-height: 14px;
    color: #66b1ff;
    cursor: pointer;
    text-decoration: underline;
  }
  .listMsg .list{
    width: 750px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 30px;
  }
  .listMsg .list .item{
    flex: 1;
    min-width: 48%;
    max-width: 48%;
    height: 140px;
    border: 1px solid #eaeaea;
    margin-top: 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 20px 0;
  }
  .listMsg .list .item img{
    width: 100px;
    height: 100px;
    background: #eaeaea;
    margin-left: 20px;
  }
  .listTit{
    width: 1200px;
    height: 50px;
    border: 1px solid #eaeaea;
    margin: 0 auto;
    display: flex;
    align-items: center;
  }
  .listTit p{
    font-size: 18px;
    line-height: 18px;
    color: #333;
    margin-left: 15px;
  }
  .listMsg{
    width: 1200px;
    display: flex;
    border: 1px solid #eaeaea;
    margin: 0 auto;
    margin-bottom: 50px;
  }
  .listMsg .cart{
    /*flex: 1;*/
    width: 500px;
    border-left: 1px solid #eaeaea;
    position: relative;
  }
  .search{
    width: 1200px;
    margin: 0 auto;
    height: 100px;
    display: flex;
    align-items: center;
  }
  .index{
    width:100%;
    height:40px;
    background:#f2f2f2;
  }
  .index-child{
    width:1200px;
    margin:0 auto;
    height:40px;
    display:flex;
    align-items:center;
    justify-content: flex-end;
  }
  .index-child .username,.index-child .quit{
    font-size: 14px;
    line-height: 14px;
    color: #333;
    cursor: pointer;
  }
  .index-child i{
    width: 2px;
    height: 14px;
    background: #333;
    margin:  0 10px;
  }
</style>
